<template>
  <main class="_main">
    <el-tree v-loading="loading" :default-expanded-keys="defaultExpanded" @node-expand="expandedChange" @node-collapse="expandedChange" :data="treeData" :props="treeProps" :expand-on-click-node="false" @node-click="nodeClickHandle" node-key="id">
      <div class="w100 flex_sb" slot-scope="{ node, data }">
        <div>{{ node.label }}</div>
        <div>
          <el-button v-if="nodeSetClick" type="text" size="mini" @click.stop="setClick(data,node)">
            修改
          </el-button>
          <el-button v-if="nodeDelClick" type="text" size="mini" @click.stop="delClick(data,node)">
            删除
          </el-button>
        </div>
      </div>
    </el-tree>
  </main>
</template>

<script>
import * as api from '../api/private/position'
export default {
  props: {
    nodeClick: {
      type: Function,
      default(row) {
        console.log('节点单击事件未定义函数')
      }
    },

    nodeDblClick: {
      type: Function,
      default(row) {
        console.log('节点双击事件未定义函数')
      }
    },
    nodeSetClick: {
      type: Function,
      default: null
    },
    nodeDelClick: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      oneClick: false,
      // 定时器
      timer: null,
      defaultExpanded: [],
      loading: false,
      once: false
    }
  },
  created() {
    // vuex
    // this.defaultExpanded = this.$store.state.defaultExpanded

    let defaultExpanded = window.sessionStorage.getItem('defaultExpanded')
    this.defaultExpanded = defaultExpanded ? JSON.parse(defaultExpanded) : []
    let defaultTunnel = window.sessionStorage.getItem('defaultTunnel')
    this.defaultTunnel = defaultTunnel ? JSON.parse(defaultTunnel) : null
  },
  mounted() {
    this.$ebs.$on('project_change', this.project_change_call)
    this.getPosition()
  },
  methods: {
    init() {
      let defaultExpanded = window.sessionStorage.getItem('defaultExpanded')
      this.defaultExpanded = defaultExpanded ? JSON.parse(defaultExpanded) : []
      this.getPosition()
    },
    project_change_call() {
      if (!this.once) {
        this.once = true
      } else {
        window.sessionStorage.removeItem('defaultTunnel')
      }
      this.getPosition()
    },
    // 获取项目下的所有数据
    async getPosition(id) {
      if (!this.$store.state.project_id) return
      this.loading = true
      let req = { projectId: this.$store.state.project_id }
      let res = await api.getProjectTree(req)
      if (res.code == 0) {
        // 递归为树节点添加可判断层数的属性
        this.layerCache = 0
        this.treeData = this.recursion(res.data)
      } else {
        this.$msg.error('获取项目详情失败')
      }
      this.loading = false
    },
    // 递归为树节点添加可判断层数的属性
    recursion(childrenArr) {
      this.layerCache += 1
      childrenArr.forEach(item => {
        item.layer = this.layerCache
        if (item.children && item.children.length) {
          this.recursion(item.children)
        }
      })
      return childrenArr
    },
    // 节点单击事件
    nodeClickHandle(row, node) {
      this._catchRow = row
      this._catchNode = node
      // 定时器，为实现双击事件
      if (!this.timer) {
        this.oneClick = true
        this.timer = setTimeout(item => {
          this.timer = null
          this.oneClick = false
          this.oneClickFun()
        }, 250)
      } else {
        clearInterval(this.timer)
        this.timer = null
        this.oneClick = false
        this.twoClickFun()
      }
    },
    // 树节点修改按钮
    setClick(data, node) {
      // 向父组件抛出事件
      this.nodeSetClick(data, node)
    },
    // 树节点删除按钮
    delClick(data, node) {
      // 向父组件抛出事件
      this.nodeDelClick(data, node)
    },
    // 单击事件
    oneClickFun() {
      // console.log(this._catchRow)
      // console.log(this._catchRow.name, this._catchRow.layer, this._catchRow.type)
      window.sessionStorage.setItem('defaultTunnel', JSON.stringify(this._catchRow))
      this.nodeClick(this._catchRow, this._catchNode)
    },
    // 双击事件
    twoClickFun() {
      this._catchNode.expanded = !this._catchNode.expanded
      this.nodeDblClick(this._catchRow, this._catchNode)
    },
    delNode(data, node) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },
    // 往树节点添加节点事件
    addNode(data, newNodeData, root = false) {
      // if (!data.children) {
      //   this.$set(data, 'children', [])
      // }
      // if (data == this.treeData) {
      if (root) {
        this.treeData.push(newNodeData)
      } else {
        data.children.push(newNodeData)
      }
    },
    // 树节点选中项发生改变
    expandedChange(data, node, components) { 
      // 查看是否存在
      let index = -1
      this.defaultExpanded.forEach((item, i) => {
        if (item == data.id) {
          index = i
        }
      })
      if (index >= 0) {
        // 存在
        this.defaultExpanded.splice(index, 1)
      } else {
        // 不存在
        this.defaultExpanded.push(data.id)
      }
      // 存储展开状态
      // vuex
      // this.$store.state.defaultExpanded = this.defaultExpanded
      // session
      window.sessionStorage.setItem('defaultExpanded', JSON.stringify(this.defaultExpanded))
    }
  },
  destroyed() {
    this.$ebs.$off('project_change', this.project_change_call)
  }
}
</script>

<style scoped>
._main {
  width: 100%;
  user-select: none;
  font-size: 16px;
}
</style>